from toolz.curried import *
from languagetools import *

article_db_path = 'article_db'

def make_path(*segments):
    import os
    return thread_last(
            segments,
            (map,str),
            list,
            (apply,os.path.join) )

def get_path(article: dict):
    gid = article['gid']
    assert type(gid) is str
    date = article['date']
    y = date.year
    m = date.month
    return thread_last(
            (article_db_path, y, m, gid),
            (apply, make_path) )

def pickle(article):
    assert type(article) is dict
    path = get_path(article)
    import os
    ensure_dirs_exist = lambda path: os.makedirs(path, exist_ok=True)
    pipe( path, os.path.dirname, ensure_dirs_exist )
    with open(path, 'wb') as fayl:
        import pickle
        pickle.dump(article, fayl, protocol=pickle.HIGHEST_PROTOCOL)
    return path

def next_month(ym):
    y, m = ym
    assert 1900 < y < 2100
    assert 0 < m < 13
    if m == 12:
        return (y + 1, 1)
    else:
        return (y, m + 1)

def is_within(ym, frm, to):
    year_good = frm[0] <= ym[0] <= to[0]
    month_good = frm[1] <= ym[1] <= to[1]
    return year_good and month_good

def opener(mode):
    return lambda path: open(path, mode=mode)

def pickles_by_ym(ym):
    y, m = ym
    directory = make_path(article_db_path, y, m)
    from operator import add
    import os
    pickles = thread_last(
            directory,
            os.listdir,
            (map, partial(make_path,directory)) )
    return pickles

def pickles_frm_to(frm,to):
    ym = frm
    pickles = []
    while is_within(ym, frm, to):
        pickles += pipe( ym, pickles_by_ym )
        ym = next_month(ym)
    return pickles

def unpickle(path):
    with open(path, 'rb') as fayl:
        import pickle
        return pickle.load(fayl)
